// 引入工具函数
const util = require('../../utils/util.js');
// 获取应用实例
const app = getApp();
// 云数据库引用
const db = wx.cloud.database();
const todosCollection = db.collection('todos');

Page({
  data: {
    taskList: [],
    filteredList: [],
    currentTab: 'all',
    searchKey: '',
    petGrowthTip: false,
    tipContent: '',
    isLoading: true,
    isCloudReady: false // 云开发是否初始化完成
  },

  onLoad(options) {
    // 等待云开发初始化完成
    if (app.globalData.openid) {
      // 已初始化完成
      this.setData({ isCloudReady: true }, () => {
        this.getTaskList();
      });
    } else {
      // 监听初始化完成事件
      app.getOpenid().then(() => {
        this.setData({ isCloudReady: true }, () => {
          this.getTaskList();
        });
      }).catch(err => {
        console.error('云初始化失败', err);
        this.setData({ isLoading: false });
        wx.showToast({
          title: '云服务初始化失败',
          icon: 'none',
          duration: 3000
        });
      });
    }

    // 监听宠物数据变化
    this.startPetWatcher();
  },

  // 启动宠物数据监听
  startPetWatcher() {
    this.petWatch = db.collection('pets').watch({
      onChange: (snapshot) => {
        if (snapshot.docChanges[0]?.dataType === 'update') {
          this.setData({
            petGrowthTip: true,
            tipContent: `宠物${snapshot.docChanges[0].doc.name}属性+${snapshot.docChanges[0].doc.latestGrowth}`
          });
          setTimeout(() => this.setData({ petGrowthTip: false }), 3000);
        }
      },
      onError: (err) => console.error('宠物数据监听失败：', err)
    });
  },

  onPullDownRefresh() {
    if (this.data.isCloudReady) {
      this.getTaskList(() => wx.stopPullDownRefresh());
    } else {
      wx.stopPullDownRefresh();
    }
  },

  // 获取任务列表
  getTaskList(callback) {
    if (!this.data.isCloudReady) return;

    const openid = app.globalData.openid;
    todosCollection.where({
      _openid: openid,
      isDeleted: false
    }).orderBy('deadline', 'asc')
      .get({
        success: (res) => {
          const taskList = res.data.map(task => ({
            ...task,
            deadlineFormat: util.formatTime(new Date(task.deadline), 'Y-M-D h:m'),
            isOverdue: task.status === 'active' && new Date(task.deadline) < new Date()
          }));
          this.setData({
            taskList,
            filteredList: taskList,
            isLoading: false
          });
          callback && callback();
        },
        fail: (err) => {
          console.error('获取任务列表失败：', err);
          wx.showToast({ title: '数据加载失败', icon: 'none' });
          this.setData({ isLoading: false });
          callback && callback();
        }
      });
  },

  // 切换筛选标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ currentTab: tab }, () => this.filterTask());
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({ searchKey: e.detail.value.trim() }, () => this.filterTask());
  },

  // 筛选任务
  filterTask() {
    const { taskList, currentTab, searchKey } = this.data;
    let filtered = [...taskList];

    if (currentTab === 'active') {
      filtered = filtered.filter(task => task.status === 'active');
    } else if (currentTab === 'completed') {
      filtered = filtered.filter(task => task.status === 'completed');
    }

    if (searchKey) {
      const key = searchKey.toLowerCase();
      filtered = filtered.filter(task => 
        task.title.toLowerCase().includes(key) || 
        task.category.toLowerCase().includes(key)
      );
    }

    this.setData({ filteredList: filtered });
  },

  // 切换任务状态
  handleTaskToggle(e) {
    if (!this.data.isCloudReady) return;

    const { taskId, status } = e.detail;
    const newStatus = status === 'active' ? 'completed' : 'active';
    
    todosCollection.doc(taskId).update({
      data: {
        status: newStatus,
        updateTime: db.serverDate()
      },
      success: () => {
        const { taskList } = this.data;
        const updatedList = taskList.map(task => 
          task._id === taskId ? { ...task, status: newStatus, isOverdue: false } : task
        );
        this.setData({ taskList: updatedList }, () => {
          this.filterTask();
          if (newStatus === 'completed') {
            this.triggerPetGrowth(taskList.find(t => t._id === taskId));
          }
        });
      },
      fail: () => wx.showToast({ title: '状态更新失败', icon: 'none' })
    });
  },

  // 触发宠物成长
  triggerPetGrowth(task) {
    wx.cloud.callFunction({
      name: 'updatePetGrowth',
      data: {
        category: task.category,
        taskId: task._id
      },
      success: (res) => console.log('宠物成长触发成功：', res),
      fail: (err) => console.error('宠物成长触发失败：', err)
    });
  },

  // 删除任务
  handleTaskDelete(e) {
    if (!this.data.isCloudReady) return;

    const taskId = e.detail.taskId;
    wx.showModal({
      title: '确认删除',
      content: '删除后任务将移入回收站，30天后自动清理',
      confirmColor: '#FF5252',
      success: (res) => {
        if (res.confirm) {
          todosCollection.doc(taskId).update({
            data: { isDeleted: true, deleteTime: db.serverDate() },
            success: () => {
              const { taskList } = this.data;
              this.setData({ taskList: taskList.filter(t => t._id !== taskId) }, () => {
                this.filterTask();
                wx.showToast({ title: '已移入回收站' });
              });
            }
          });
        }
      }
    });
  },

  // 跳转至任务编辑页
  goToTaskEdit(e) {
    const taskId = e.currentTarget.dataset.taskId || '';
    wx.navigateTo({ url: `/pages/taskEdit/taskEdit?taskId=${taskId}` });
  },

  // 关闭提示
  closeTip() {
    this.setData({ petGrowthTip: false });
  },

  // 页面卸载时关闭监听
  onUnload() {
    this.petWatch && this.petWatch.close();
  }
});

      
      
  
  
  